import Foundation

class AIService {
    static let shared = AIService()
    private init() {}

    func sendRequest(imageURL: String) async throws -> String {

        let url = URL(string: "https://intangily-misrhymed-ellyn.ngrok-free.dev/process")!

        let body: [String: Any] = [
            "image_url": imageURL
        ]

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONSerialization.data(withJSONObject: body)

        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 60
        config.timeoutIntervalForResource = 60
        let session = URLSession(configuration: config)

        let (data, response) = try await session.data(for: request)

        let rawString = String(data: data, encoding: .utf8) ?? "<non-UTF8>"
        print("🔵 RAW RESPONSE:\n\(rawString)")

        if let http = response as? HTTPURLResponse, http.statusCode >= 300 {
            throw NSError(
                domain: "AIService",
                code: http.statusCode,
                userInfo: [NSLocalizedDescriptionKey: rawString]
            )
        }


        if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
           let message = json["message"] as? String {
            return message
        }

        return rawString
    }
}
